import allure
import requests
from common.api.log_tools import log
from data.api.env import URL

class BaseRequest:
    sess=requests.session()
    @classmethod
    def send_request(cls,**kwargs):
        try:
            rp=cls.sess.request(**kwargs)
        except Exception as e:
            log.error(e)
            raise e
        else:
            return rp


    @classmethod
    def execute_api_request(cls,request={"epic":"pinter项目","feature":"金融项目","story":"登录接口","method":"post","url":"/bank/api/login","cookies":None,"headers":None},
                            parametrize={"title":"请输入正确的用户名称和密码,登陆成功","data":{"userName":"admin","password":"123456"},"expect":{"status_code":'0',"msg":"success"},"params":None,"json":None,"files":None}):
        # log.debug(request,parametrize)
        method=request["method"]
        allure.attach(method, "请求方法:", attachment_type=allure.attachment_type.TEXT)
        url=URL+request["url"]
        allure.attach(url, "接口地址:", attachment_type=allure.attachment_type.TEXT)
        cookies=request["cookies"]
        if cookies is not None:
            allure.attach(cookies, "cookies信息:", attachment_type=allure.attachment_type.TEXT)
        headers=request["headers"]
        if headers is not None:
            allure.attach(headers, "headers信息:", attachment_type=allure.attachment_type.TEXT)
        data=parametrize["data"]
        if data is not None:
            allure.attach(str(data), "data信息:", attachment_type=allure.attachment_type.TEXT)
        files=parametrize["files"]
        if files is not None:
            allure.attach(str(files), "files信息:", attachment_type=allure.attachment_type.TEXT)
        params=parametrize["params"]
        if params is not None:
            allure.attach(str(params), "params信息:", attachment_type=allure.attachment_type.TEXT)
        json=parametrize["json"]
        if json is not None:
            allure.attach(str(json), "json信息:", attachment_type=allure.attachment_type.TEXT)
        # log.debug(f"method={method},url={url},cookies={cookies},headers={headers},data={data},json={json},files={files},params={params}")
        rp=cls.send_request(method=method,url=url,cookies=cookies,headers=headers,data=data,json=json,files=files,params=params)
        allure.attach(rp.text, "接口返回结果:", attachment_type=allure.attachment_type.TEXT)
        log.debug(rp.text)
        return rp

if __name__ == '__main__':
    BaseRequest.execute_api_request()